package jp.syuriken.snsw.terenaibot.format;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * TODO snsoftware
 * 
 * @author $Author: snswinhaiku.lo@gmail.com $ */
public class PrecompiledProperty implements PrecompiledSyntax {
	
	private final PrecompiledSyntaxGroup propertyName;
	
	private final PrecompiledSyntaxGroup prefix;
	
	private final PrecompiledSyntaxGroup defaultValue;
	

	/**
	 * インスタンスを生成する。
	 * @throws FormatSyntaxException 
	 */
	public PrecompiledProperty(ArrayList<PrecompiledSyntaxGroup> syntaxGroups) throws FormatSyntaxException {
		PrecompiledSyntaxGroup[] syntaxes = syntaxGroups.toArray(new PrecompiledSyntaxGroup[syntaxGroups.size()]);
		switch (syntaxes.length) {
			case 1:
				prefix = null;
				propertyName = syntaxes[0];
				defaultValue = null;
				break;
			case 2:
				prefix = syntaxes[0];
				propertyName = syntaxes[1];
				defaultValue = null;
				break;
			case 3:
				prefix = syntaxes[0];
				propertyName = syntaxes[1];
				defaultValue = syntaxes[2];
				break;
			default:
				throw new FormatSyntaxException("Propertyは1つから3つまでの引数を取ります。got arguments: " + Arrays.toString(syntaxes));
		}
	}
	
	@Override
	public String format(CompileArg compileArg) throws FormatSyntaxException {
		if (prefix == null) {
			return compileArg.getProperty(propertyName.format(compileArg));
		} else if (defaultValue == null) {
			return compileArg.getProperty(prefix.format(compileArg), propertyName.format(compileArg));
		} else {
			return compileArg.getProperty(prefix.format(compileArg), propertyName.format(compileArg),
					defaultValue.format(compileArg));
		}
	}
	
	@Override
	public String toString() {
		return String.format("Property{%s:%s=%s}", prefix == null ? "" : prefix, propertyName, defaultValue == null
				? "" : defaultValue);
	}
	
}
